<?php


class AjaxController implements Controller
{
    /**
     * @var array View
     */
    protected $_Views;
    
    protected $_errors = array();
    
    public function __construct($actions)
    {
        $actions = json_decode($actions);
        self::JSONErrorHandler();
        if (is_array($actions)) {
            foreach ($actions as $action) {
                $this->createView($action);
            }
        } else {
            $this->createView($actions);
        }
    }
    
    public function __toString()
    {
        $ret = array();
        foreach ($this->_Views as $View) {
            $ret[] = $this->parse($View);
        }
        return implode(",", $ret);
    }
    
    protected function createView($action)
    {
        if (!isset($action->view)) {
            throw new InvalidArgumentException('Action without View');
        }
        if (isset($action->params) && !is_a($action->params)) {
            throw new InvalidArgumentException('Action with invalid params (not object)');
        }
        $view = $action->view;
        $params = isset($actions->params) ? $action->params : array();
        try {
            $this->_Views[] = new $view($params);
        }
        catch (AutoloaderException $e) {
            $this->errors[] = $e->getMessage();
        }
    }
    
    protected function parse(View $View)
    {
        return sprintf('{ "modul": "%s", "tpl": "%s", "data": %s }', $View->module(), $View->templateFile(), json_encode($View->data()));
    }
    
    public static function JSONErrorHandler()
    {
        //PHP >= 5.3
        /*switch(json_last_error())
        {
            case JSON_ERROR_DEPTH:
                throw new JSONErrorException('Stack depth overflow');
                return true;
            case JSON_ERROR_CTRL_CHAR:
                throw new JSONErrorException('Unexpected control character');
                return true;
            case JSON_ERROR_SYNTAX:
                throw new JSONErrorException('Syntax error, malformed JSON');
                return true;
            //case JSON_ERROR_NONE:
                // ' No errors';
              //  break;
        }*/
        return false;
    }
}

class JSONErrorException extends ErrorException
{}

class AjaxControllerException extends PhException
{}